package com.gexiaobao.pigeon.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.model.bean.ScanPigeonsResponse
import com.gexiaobao.pigeon.app.model.param.CancelPayLoftParam
import com.gexiaobao.pigeon.app.model.param.ConsumeApplyLoftParam
import com.gexiaobao.pigeon.app.model.param.LoftPayInfoParam
import com.gexiaobao.pigeon.app.model.param.PayParam
import com.gexiaobao.pigeon.app.util.DESUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityLoftPayInfoBinding
import com.gexiaobao.pigeon.ui.adapter.PigeonsAdapter
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.viewmodel.PayViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat


/**
 * @Author      : hxw
 * @Date        : 2024/4/2 14:46
 * @Describe    : 赛鸽缴费
 */
class LoftPayInfoActivity : BaseActivity<PayViewModel, ActivityLoftPayInfoBinding>() {

    private var mOrderId = 0
    private var mUniqueId = ""
    private var payPassDialog: PayPassDialog? = null
    private var payDialog: RxPayDialog? = null
    private val mAdapter: PigeonsAdapter by lazy { PigeonsAdapter(arrayListOf()) }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun initView(savedInstanceState: Bundle?) {
        val dataScan = intent.getParcelableExtra<ScanPigeonsResponse>("dataBean")
        if (dataScan != null) {
            mUniqueId = dataScan.uniqueId
            val param = LoftPayInfoParam(
                pigeonIds = dataScan.pigeonIds,
                uniqueId = mUniqueId,
                orgId = dataScan.orgId,
            )
            mViewModel.genLoftPayInfo(param)
        }
        mDatabind.includeBar.toolbar.initClose {
            finish()
        }

        //设置字间距
        val textPaint = mDatabind.tvLoftPayTitle.paint
        textPaint.letterSpacing = 0.1f

        mDatabind.recyclerViewPigeons.init(GridLayoutManager(this, 2), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(this, 10f))
        )
        mDatabind.recyclerViewPigeons.adapter = mAdapter
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.btnLoftPay) {
            when (it) {
                mDatabind.btnLoftPay -> {
                    showLoading(getString(R.string.loading))
                    val param = ConsumeApplyLoftParam(
                        orderId = mOrderId,
                        uniqueId = mUniqueId
                    )
                    mViewModel.consumeApplyLoftPigeon(param)
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        mViewModel.loftPayInfoResult.observe(this) {
            if (it != null) {
                mOrderId = it.id
                mDatabind.data = it
                mDatabind.tvTotalPigeon.text = getString(R.string.total) + it.ringIds.size + "  x  " + it.totalMoney + getString(R.string.yuan)
                mDatabind.includeBar.toolbar.initClose(it.orgName) {
                    finish()
                }
                mAdapter.setList(it.ringIds)
                mAdapter.notifyDataSetChanged()
            }
        }
        /** 确认支付 */
        mViewModel.payResult.observe(this) { resultState ->
            parseState(resultState, {
                payPassDialog?.dismiss()
                paySuccess()
            }, {
                RxToast.showToast(it.msg)
            })
        }
        /** 二维码公棚赛鸽申请支付 */
        mViewModel.consumeApplyLoftResult.observe(this) {
            dismissLoading()
            showBottomPayDialog()
        }
    }

    private fun paySuccess() {
        payDialog!!.showBottomBtnSingle()
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent(getString(R.string.payment_success))
    }

    private fun showBottomPayDialog() {
        payPassDialog = PayPassDialog(this)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            @SuppressLint("SetTextI18n")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {
            }

            override fun onPayClose() {
                val body = CancelPayLoftParam(
                    orderId = mOrderId
                )
                mViewModel.cancelPayLoftPigeon(body)
                RxToast.showToast(getString(R.string.Turn_off_Payment))
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
            }

            override fun onPassFinish(verifyCode: String?) {
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val body = PayParam(mOrderId, verifyCode.toString())
                    mViewModel.commitPay(body)
                }, lifecycleScope)
            }
        })
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(this)
        payDialog!!.loadingDialog()
        payDialog!!.setCancelListener {
            payDialog!!.dismiss()
            finish()
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 扫描二维码/条码回传
        if (requestCode == 1001122 && resultCode == Activity.RESULT_OK) {
            val content = data!!.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
            if (!content.isNullOrEmpty()) {
                val result = DESUtils.decryptDES(content)
                val dataScan = Gson().fromJson(result, ScanPigeonsResponse::class.java)
                if (dataScan != null) {
                    mUniqueId = dataScan.uniqueId
                    val param = LoftPayInfoParam(
                        pigeonIds = dataScan.pigeonIds,
                        uniqueId = mUniqueId,
                        orgId = dataScan.orgId,
                    )
                    mViewModel.genLoftPayInfo(param)
                }
            }
        }
    }
}